import { Decorator } from "../core/Decorator";
import { Tick } from "../core/Tick";
import { ActionStatus } from "../core/BaseNode";

export class MaxTime extends Decorator {

    maxTime: number = 0;

    constructor(params?: any) {
        super(params);
        params = params || {maxTime: 0};
        this.name = 'MaxTime';
        this.title = 'Max <maxTime>ms';
        this.properties = params
        this.maxTime = params.maxTime || 0;
    }

    open(tick: Tick) {
        let startTime = (new Date()).getTime();
        tick.blackboard.set('startTime', startTime, tick.tree.id, this.id);
    }

    tick(tick: Tick) : ActionStatus {
        if (!this.child) {
            return ActionStatus.ERROR;
        }
        let currentTime = (new Date()).getTime();
        let startTime = tick.blackboard.get('startTime', tick.tree.id, this.id);
        let status = this.child._execute(tick);
        if (currentTime - startTime > this.maxTime) {
            return ActionStatus.FAILURE;
        }
        return status;
    }
}